#!/bin/bash
# CPU占用对比测试：enrigindec vs avdec_h264
# 测试硬件解码器和软件解码器的CPU占用差异

set -e

export GST_PLUGIN_PATH=/root/clients/main/gstreamer_basic/build:$GST_PLUGIN_PATH

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  解码器CPU占用对比测试${NC}"
echo -e "${BLUE}  enrigindec (硬件) vs avdec_h264 (软件)${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 检查测试视频文件
TEST_VIDEO="/root/test_data/video/sample.h264"
if [ ! -f "$TEST_VIDEO" ]; then
    echo -e "${YELLOW}警告: 测试视频不存在，使用videotestsrc生成测试数据${NC}"
    TEST_VIDEO=""
fi

# 测试时长（秒）
TEST_DURATION=10
FRAME_COUNT=300  # 30fps * 10秒

echo -e "${GREEN}测试配置:${NC}"
echo "  - 测试时长: ${TEST_DURATION}秒"
echo "  - 帧数: ${FRAME_COUNT}帧"
echo "  - 分辨率: 1920x1080"
echo ""

# 函数：监控CPU占用
monitor_cpu() {
    local pid=$1
    local output_file=$2
    local interval=0.5
    
    echo "timestamp,cpu_percent,mem_mb" > "$output_file"
    
    while kill -0 $pid 2>/dev/null; do
        # 获取CPU和内存占用
        local stats=$(ps -p $pid -o %cpu,%mem,rss --no-headers 2>/dev/null || echo "0 0 0")
        local cpu=$(echo $stats | awk '{print $1}')
        local mem_kb=$(echo $stats | awk '{print $3}')
        local mem_mb=$(echo "scale=2; $mem_kb / 1024" | bc)
        local timestamp=$(date +%s.%N)
        
        echo "$timestamp,$cpu,$mem_mb" >> "$output_file"
        sleep $interval
    done
}

# 函数：计算统计数据
calculate_stats() {
    local file=$1
    
    # 跳过前2秒的数据（预热）
    local data=$(tail -n +5 "$file" | awk -F',' '{print $2}')
    
    if [ -z "$data" ]; then
        echo "0 0 0 0"
        return
    fi
    
    local avg=$(echo "$data" | awk '{sum+=$1; count++} END {if(count>0) print sum/count; else print 0}')
    local max=$(echo "$data" | sort -n | tail -1)
    local min=$(echo "$data" | sort -n | head -1)
    
    # 计算标准差
    local stddev=$(echo "$data" | awk -v avg=$avg '{sum+=($1-avg)^2; count++} END {if(count>0) print sqrt(sum/count); else print 0}')
    
    echo "$avg $max $min $stddev"
}

# 测试1: avdec_h264 (软件解码)
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}测试 1: avdec_h264 (软件解码)${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

CPU_LOG_SW="cpu_avdec_h264.csv"

if [ -n "$TEST_VIDEO" ]; then
    # 使用真实视频文件
    gst-launch-1.0 -q \
        filesrc location="$TEST_VIDEO" ! \
        h264parse ! \
        avdec_h264 ! \
        fakesink sync=true &
else
    # 使用videotestsrc
    gst-launch-1.0 -q \
        videotestsrc num-buffers=$FRAME_COUNT pattern=ball ! \
        video/x-raw,format=I420,width=1920,height=1080,framerate=30/1 ! \
        x264enc bitrate=4000 tune=zerolatency ! \
        h264parse ! \
        avdec_h264 ! \
        fakesink sync=true &
fi

GST_PID=$!
echo "  进程PID: $GST_PID"
echo "  正在监控CPU占用..."

# 监控CPU
monitor_cpu $GST_PID "$CPU_LOG_SW" &
MONITOR_PID=$!

# 等待测试完成
wait $GST_PID 2>/dev/null
wait $MONITOR_PID 2>/dev/null

# 计算统计
read avg_sw max_sw min_sw stddev_sw <<< $(calculate_stats "$CPU_LOG_SW")

echo -e "${GREEN}  完成!${NC}"
echo "  平均CPU: ${avg_sw}%"
echo "  最大CPU: ${max_sw}%"
echo "  最小CPU: ${min_sw}%"
echo "  标准差: ${stddev_sw}%"
echo ""

sleep 2

# 测试2: enrigindec (硬件解码)
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${YELLOW}测试 2: enrigindec (硬件解码)${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

CPU_LOG_HW="cpu_enrigindec.csv"

if [ -n "$TEST_VIDEO" ]; then
    # 使用真实视频文件
    gst-launch-1.0 -q \
        filesrc location="$TEST_VIDEO" ! \
        h264parse ! \
        enrigindec codec=h264 ! \
        fakesink sync=true &
else
    # 使用videotestsrc
    gst-launch-1.0 -q \
        videotestsrc num-buffers=$FRAME_COUNT pattern=ball ! \
        video/x-raw,format=I420,width=1920,height=1080,framerate=30/1 ! \
        x264enc bitrate=4000 tune=zerolatency ! \
        h264parse ! \
        enrigindec codec=h264 ! \
        fakesink sync=true &
fi

GST_PID=$!
echo "  进程PID: $GST_PID"
echo "  正在监控CPU占用..."

# 监控CPU
monitor_cpu $GST_PID "$CPU_LOG_HW" &
MONITOR_PID=$!

# 等待测试完成
wait $GST_PID 2>/dev/null
wait $MONITOR_PID 2>/dev/null

# 计算统计
read avg_hw max_hw min_hw stddev_hw <<< $(calculate_stats "$CPU_LOG_HW")

echo -e "${GREEN}  完成!${NC}"
echo "  平均CPU: ${avg_hw}%"
echo "  最大CPU: ${max_hw}%"
echo "  最小CPU: ${min_hw}%"
echo "  标准差: ${stddev_hw}%"
echo ""

# 对比结果
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  对比结果${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

printf "%-20s %-15s %-15s %-15s %-15s\n" "解码器" "平均CPU(%)" "最大CPU(%)" "最小CPU(%)" "标准差(%)"
echo "────────────────────────────────────────────────────────────────────────────"
printf "%-20s %-15.2f %-15.2f %-15.2f %-15.2f\n" "avdec_h264 (软件)" "$avg_sw" "$max_sw" "$min_sw" "$stddev_sw"
printf "%-20s %-15.2f %-15.2f %-15.2f %-15.2f\n" "enrigindec (硬件)" "$avg_hw" "$max_hw" "$min_hw" "$stddev_hw"
echo ""

# 计算节省百分比
if [ $(echo "$avg_sw > 0" | bc) -eq 1 ]; then
    cpu_saving=$(echo "scale=2; ($avg_sw - $avg_hw) / $avg_sw * 100" | bc)
    echo -e "${GREEN}CPU节省: ${cpu_saving}%${NC}"
    
    if [ $(echo "$cpu_saving > 50" | bc) -eq 1 ]; then
        echo -e "${GREEN}✓ 硬件解码显著降低CPU占用${NC}"
    elif [ $(echo "$cpu_saving > 20" | bc) -eq 1 ]; then
        echo -e "${YELLOW}✓ 硬件解码有效降低CPU占用${NC}"
    else
        echo -e "${YELLOW}! 硬件解码CPU节省有限${NC}"
    fi
fi

echo ""
echo -e "${BLUE}详细数据已保存:${NC}"
echo "  - $CPU_LOG_SW (软件解码)"
echo "  - $CPU_LOG_HW (硬件解码)"
echo ""

# 生成简单的ASCII图表
echo -e "${BLUE}CPU占用趋势 (简化):${NC}"
echo ""
echo "avdec_h264 (软件):"
tail -n 20 "$CPU_LOG_SW" | awk -F',' 'NR>1 {
    cpu=$2; 
    bars=int(cpu/5); 
    printf "  %6.2f%% ", cpu; 
    for(i=0;i<bars;i++) printf "█"; 
    printf "\n"
}'
echo ""
echo "enrigindec (硬件):"
tail -n 20 "$CPU_LOG_HW" | awk -F',' 'NR>1 {
    cpu=$2; 
    bars=int(cpu/5); 
    printf "  %6.2f%% ", cpu; 
    for(i=0;i<bars;i++) printf "█"; 
    printf "\n"
}'
echo ""

echo -e "${GREEN}测试完成!${NC}"
